import axios from 'axios'

// 根据环境变量设置 API 基础 URL
const getApiBaseUrl = () => {
  if (process.env.NODE_ENV === 'production') {
    // 生产环境：使用正确的后端地址
    return process.env.VITE_API_BASE_URL || 'https://springboot-qx6h-195220-5-1384122486.sh.run.tcloudbase.com/api'
  } else {
    // 开发环境指向本地后端服务
    return 'http://localhost:8123/api'
  }
}

const API_BASE_URL = getApiBaseUrl()

// 创建axios实例
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: false, // 跨域请求不携带cookie
})

// 封装SSE连接
export const connectSSE = (url, params, onMessage, onError) => {
  // 构建带参数的URL
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
  
  const fullUrl = `${API_BASE_URL}${url}?${queryString}`
  
  // 创建EventSource
  const eventSource = new EventSource(fullUrl)
  
  eventSource.onmessage = event => {
    let data = event.data
    
    // 检查是否是特殊标记
    if (data === '[DONE]') {
      if (onMessage) onMessage('[DONE]')
    } else {
      // 处理普通消息
      if (onMessage) onMessage(data)
    }
  }
  
  eventSource.onerror = error => {
    console.error('SSE连接错误:', error)
    console.error('请求URL:', fullUrl)
    console.error('错误详情:', {
      readyState: eventSource.readyState,
      url: eventSource.url
    })
    
    // 检查是否是CORS错误
    if (eventSource.readyState === EventSource.CLOSED) {
      console.error('SSE连接被关闭，可能是CORS问题或服务器错误')
    }
    
    if (onError) onError(error)
    eventSource.close()
  }
  
  // 返回eventSource实例，以便后续可以关闭连接
  return eventSource
}

// AI恋爱大师聊天
export const chatWithLoveApp = (message, chatId) => {
  return connectSSE('/ai/love_app/chat/sse', { message, chatId })
}

// AI超级智能体聊天
export const chatWithManus = (message, chatId) => {
  return connectSSE('/ai/manus/chat', { message, chatId })
}

export default {
  chatWithLoveApp,
  chatWithManus
}